﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.BabelCam.Infrastructure.Helpers
{
    using System;
    using Microsoft.Samples.BabelCam.Infrastructure.Models;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;

    public class CloudStorageInitializer
    {
        public static void InitializeCloudStorage(CloudStorageAccount account)
        {
            CloudTableClient cloudTableClient = account.CreateCloudTableClient();

            CreateWordsTable(cloudTableClient);
            CreatePushNotificationTable(cloudTableClient);
            CreateUserTable(cloudTableClient);
            CreateUserPrivilegeTable(cloudTableClient);
            CreateSilverlightClientAccessPolicy(account.CreateCloudBlobClient());
        }

        private static void CreatePushNotificationTable(CloudTableClient cloudTableClient)
        {
            cloudTableClient.CreateTableIfNotExist(UserTablesServiceContext.PushUserTableName);

            // Execute conditionally for development storage only.
            if (cloudTableClient.BaseUri.IsLoopback)
            {
                var context = cloudTableClient.GetDataServiceContext();
                var entity = new PushUserEndpoint { UserId = "UserName", ChannelUri = "http://tempuri", TileCount = 0 };

                context.AddObject(UserTablesServiceContext.PushUserTableName, entity);
                context.SaveChangesWithRetries();
                context.DeleteObject(entity);
                context.SaveChangesWithRetries();
            }
        }

        private static void CreateUserTable(CloudTableClient cloudTableClient)
        {
            cloudTableClient.CreateTableIfNotExist(UserTablesServiceContext.UserTableName);

            // Execute conditionally for development storage only.
            if (cloudTableClient.BaseUri.IsLoopback)
            {
                var context = cloudTableClient.GetDataServiceContext();
                var entity = new User { Name = "UserName", Email = "user@email.com" };

                context.AddObject(UserTablesServiceContext.UserTableName, entity);
                context.SaveChangesWithRetries();
                context.DeleteObject(entity);
                context.SaveChangesWithRetries();
            }
        }

        private static void CreateUserPrivilegeTable(CloudTableClient cloudTableClient)
        {
            cloudTableClient.CreateTableIfNotExist(UserTablesServiceContext.UserPrivilegeTableName);

            // Execute conditionally for development storage only.
            if (cloudTableClient.BaseUri.IsLoopback)
            {
                var context = cloudTableClient.GetDataServiceContext();
                var entity = new UserPrivilege { UserId = "UserId", Privilege = "Privilege" };

                context.AddObject(UserTablesServiceContext.UserPrivilegeTableName, entity);
                context.SaveChangesWithRetries();
                context.DeleteObject(entity);
                context.SaveChangesWithRetries();
            }
        }

        private static void CreateWordsTable(CloudTableClient cloudTableClient)
        {
            cloudTableClient.CreateTableIfNotExist(TranslatedWordsServiceContext.TranslatedWordsTableName);

            // Execute conditionally for development storage only.
            if (cloudTableClient.BaseUri.IsLoopback)
            {
                var context = cloudTableClient.GetDataServiceContext();
                var entity = new WordsEntity(string.Empty, string.Empty, Guid.NewGuid().ToString());

                context.AddObject(TranslatedWordsServiceContext.TranslatedWordsTableName, entity);
                context.SaveChangesWithRetries();
                context.DeleteObject(entity);
                context.SaveChangesWithRetries();
            }
        }

        private static void CreateSilverlightClientAccessPolicy(CloudBlobClient cloudBlobClient)
        {
            var container = cloudBlobClient.GetContainerReference("$root");
            container.CreateIfNotExist();
            container.SetPermissions(
                new BlobContainerPermissions
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });

            var blob = cloudBlobClient.GetBlobReference("clientaccesspolicy.xml");
            blob.Properties.ContentType = "text/xml";
            blob.UploadText(
                @"<?xml version=""1.0"" encoding=""utf-8""?>
                <access-policy>
                  <cross-domain-access>
                    <policy>
                      <allow-from http-methods=""*"" http-request-headers=""*"">
                        <domain uri=""*"" />
                        <domain uri=""http://*"" />
                      </allow-from>
                      <grant-to>
                        <resource path=""/"" include-subpaths=""true"" />
                      </grant-to>
                    </policy>
                  </cross-domain-access>
                </access-policy>");
        }
    }
}
